package com.stud.seckill.service.listener;

import com.alibaba.fastjson.JSON;
import com.stud.seckill.common.config.CacheService;
import com.stud.seckill.common.enums.CacheKeyEnum;
import com.stud.seckill.common.exception.Asserts;
import com.stud.seckill.entity.vo.UserOrderDTO;
import com.stud.seckill.service.SeckillOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MyRabbitListener {

    @Autowired
    private SeckillOrderService seckillOrderService;
    @Autowired
    private CacheService cacheService;

    /**
     * 秒杀订单监听
     * @param msg
     */
    @RabbitListener(queues = "seckillOrder")
    public void defaultListener(String msg) {

        UserOrderDTO params = JSON.parseObject(msg, UserOrderDTO.class);
        Long userId = params.getUserId();
        Long goodsId = params.getGoodsId();
        log.info(" 秒杀队列监听 用户ID：{}， 商品ID：{}", userId, goodsId);
        // 查询抢到的标记
        Boolean isHasOrder = cacheService.hasKey(CacheKeyEnum.秒杀监控数据, "orderSuc:userId"+userId+"goodsId"+goodsId);
        if (!isHasOrder) {
            Asserts.fail("没有抢到");
        }
        seckillOrderService.saveOrder(userId, goodsId);

        // cacheService.delete(CacheKeyEnum.秒杀监控数据, "orderSuc:userId"+userId+"goodsId"+goodsId);
    }

}
